package com.tastesport.chat.controller;

import com.tastesport.chat.model.common.HttpResult;
import com.tastesport.chat.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping(value = "/api/file")
public class FileController {

    @Autowired
    private CommonService commonService;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public HttpResult upload(MultipartFile file) {
        try {
            HttpResult result = new HttpResult();
            long uploadpicsize = 524288; // 上传图片大小限制(bt) 默认512*1024
            // 判断文件大小
            if (!file.isEmpty() && file.getSize() < uploadpicsize) {
                // 上传图片服务器并返回图片url
                String picurl = commonService.uploadFile(file, null);
                if (picurl != null) {
                    result.setCode(0);
                    result.setMsg(picurl);
                } else {
                    result.setCode(-1);
                    result.setMsg("上传失败");
                }
            } else {
                result.setCode(1);
                result.setMsg("文件大于" + (uploadpicsize / 1024) + "KB");
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
